<?php

namespace Trois\Lib;

class Cvs
{
    /**
     * 缓存连接参数
     * @access protected
     */
    protected array $options = [
        'temp' => EASYSWOOLE_ROOT . "/Temp/Cvs/"
    ];

    /**
     * 架构函数
     * @access public
     */
    public function __construct(string $temp = "")
    {

        $temp && $this->options['temp'] = $temp;

        if (substr($this->options['temp'], -1) != '/') $this->options['temp'] .= '/';

        $this->init();
    }

    /**
     * 初始化检查
     * @access private
     * @return boolean
     */
    private function init(): void
    {
        if (!is_dir($this->options['temp'])) {
            mkdir($this->options['temp']);
        }
    }

    /**
     * 取得变量的存储文件名
     * @access private
     * @param string $name 缓存变量名
     * @return string
     */
    private function filename(string $name): string
    {
        return $this->options['temp'] . $name;
    }

    /**
     * 删除文件
     * @access public
     * @param string $name 缓存变量名
     * @return boolean
     */
    public function rm(string $name): bool
    {
        return unlink($this->filename($name));
    }


    /**
     * 数据导出到excel(csv文件)
     * @param string $fileName
     * @param array $tileArray
     * @param array $dataArray
     */
    public function export_excel(string $fileName, array $tileArray, array $dataArray): void
    {

        $filename = $this->filename($fileName);

        // 打开两个资源，一个指向要写入的文件，一个指向内存
        $fileResource = fopen($filename, "w");
        $memResource = fopen('php://memory', 'w');

        fputcsv($memResource, $tileArray);

        foreach ($dataArray as $index => $item) {

            // 先将数据写入内存
            fputcsv($memResource, $item);

            // 根据数据的大小批量将是数据从内存拷贝到文件
            if ($index % 1000 == 0) {
                // 将文件指针移到开头位置
                rewind($memResource);
                // 流copye
                stream_copy_to_stream($memResource, $fileResource);
                // 清空内存中数据
                ftruncate($memResource, 0);
            }

        }

        rewind($memResource);

        stream_copy_to_stream($memResource, $fileResource);
        fclose($fileResource);
        fclose($memResource);

    }

    /**
     * 数据导出到file
     * @param string $fileName
     * @param string $data
     */
    public function export_file(string $fileName, string $data): void
    {

        $filename = $this->filename($fileName);


        $file = fopen($filename, "w");

        $pieces = str_split($data, 1024);
        foreach ($pieces as $piece) {
            fwrite($file, $piece, strlen($piece));
        }

        fclose($file);

    }

    public function exist(string $name): bool
    {
        $filename = $this->filename($name);
        return is_file($filename);
    }
}